//
//  WBComposeTypeView.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/31.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit
import pop

//撰写微博
class WBComposeTypeView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    //返回按钮X
    @IBOutlet weak var backBtnCenterXCons: NSLayoutConstraint!
    //关闭按钮X
    @IBOutlet weak var closeBtnCenterXCons: NSLayoutConstraint!
    //返回按钮
    @IBOutlet weak var backBtn: UIButton!

    //定义按钮数组
    private let buttonInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "WBComposeViewController"],
                              ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                              ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                              ["imageName": "tabbar_compose_lbs", "title": "签到"],
                              ["imageName": "tabbar_compose_review", "title": "点评"],
                              ["imageName": "tabbar_compose_more", "title": "更多","actionName": "clickMore"],
                              ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                              ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                              ["imageName": "tabbar_compose_music", "title": "音乐"],
                              ["imageName": "tabbar_compose_shooting", "title": "拍摄"]]

    //完成回调
    private var completionBlock: ((_ clsName: String?) -> ())?

    //加载xib
    class func composeTypeView() -> WBComposeTypeView {
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        // xib默认加载 600*600
        v.frame = UIScreen.main.bounds
        return v
    }
    

    //显示当前视图
    func show(completion: @escaping (_ clsName: String?) -> ()) {

        //记录闭包
        completionBlock = completion

        //1. 将当前视图添加到 根视图控制器的 view
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else{
            return
        }

        vc.view.addSubview(self)

        //添加动画
        showCurrentView()
    }


//MARK: - 动画方法扩展
    private func showCurrentView() {

        //渐变背景动画设置
        //1.创建动画
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.5

        //2.添加到视图
        pop_add(anim, forKey: nil)

        showButtons()
        
    }

    //弹力显示所有按钮
    private func showButtons() {
        //1.获取 scrollView的子视图的第 0 个视图
        let v = scrollView.subviews[0]

        //2. 遍历 v 中所有按钮
        for (i,btn) in v.subviews.enumerated() {
            // 创建弹性动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //加的值随便设
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            //弹力系数，范围为0-20
            anim.springBounciness = 8
            //弹力速度，范围为0-20
            anim.springSpeed = 8
            //动画启动时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025

            btn.pop_add(anim, forKey: nil)


        }

    }

//MARK: 隐藏按钮动画
    private func hideButton() {
        //1. 根据contentoffset 判断当前显示的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]

        //2.遍历v的所有按钮
        for (i,btn) in v.subviews.enumerated().reversed() {
            //1. 创建动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)

            //2. 设置动画属性
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350

            //动画启动时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025

            //3.添加动画
            btn.layer.pop_add(anim, forKey: nil)

            //监听第0个按钮,即最后一个按钮
            if i==0 {
                anim.completionBlock = { _, _ in
                    self.hideCurrentView()
                }
            }
        }
    }

    //隐藏当前视图,当最后一个按钮下移完成后再执行
    private func hideCurrentView() {
        //1.创建动画
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25

        //2.添加到视图
        pop_add(anim, forKey: nil)

        //3.添加完成监听方法
        anim.completionBlock = { _, _ in
            self.removeFromSuperview()
        }
    }


    @IBAction func close() {
        hideButton()
    }



    override func awakeFromNib() {
        setupUI()
    }

    private func setupUI() {

        //0. 强行更新布局
        layoutIfNeeded()

        //1. 向scrollView添加视图
        let rect = scrollView.bounds
        let width = scrollView.bounds.width

        for i in 0..<2 {
            let v = UIView(frame:rect.offsetBy(dx: CGFloat(i)*width, dy: 0))
            //2. 向视图添加按钮
            addButtons(v: v, idx: i*6)

            //3.将视图添加到 scrollView
            scrollView.addSubview(v)
        }

        //设置scrollView
        scrollView.contentSize = CGSize(width: 2 * width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        //禁用滚动
        scrollView.isScrollEnabled = false

    }

    //MARK:监听
    //点击更多
    @objc private func clickMore() {
        print("点击更多")
        //scrollView滚到第二页
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)

        //显示返回按钮，两按钮分开
        let margin = scrollView.bounds.width/6
        backBtn.isHidden = false
        backBtnCenterXCons.constant -= margin
        closeBtnCenterXCons.constant += margin

        UIView.animate(withDuration: 0.25) {
            self.layoutIfNeeded()
        }

    }

    @objc private func clickButton(selectedBtn: WBComposeTypeButton) {
        print("点我了\(selectedBtn)")

        //1. 判断当前显示视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]

        //2.遍历btn,选中的按钮放大
        for (i,btn) in v.subviews.enumerated() {

            //1> 缩放动画
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)

            let scale = (selectedBtn == btn) ? 1.5: 0.5
            //x,y在系统中使用 CGPoint 表示，如果需要转成id，需要用‘NSValue’ 包装
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.duration = 0.5

            btn.pop_add(scaleAnim, forKey: nil)

            //渐变动画
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5

            btn.pop_add(alphaAnim, forKey: nil)

            //3> 监听
            if i == 0 {
                alphaAnim.completionBlock = {_, _ in
                    print("完成回调展现控制器")
                    //执行完成闭包
                    self.completionBlock?(selectedBtn.clsName)

                }
            }

        }

    }


    func addButtons(v: UIView, idx: Int) {

        //从idx开始，添加6个按钮
        let count = 6

        for i in idx..<(idx+count) {

            if i >= buttonInfo.count {
                break
            }

            //从数组字典中获取 图像名称
            let dict = buttonInfo[i]
            guard let imageName = dict["imageName"],
                  let title = dict["title"] else{
                continue
            }

            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            v.addSubview(btn)

            //添加监听方法
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                //FIXME: - 不知点击哪个
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }

            //设置要展现的类名 - 不需要任何判断，有了就设置，没有就不设置
            btn.clsName = dict["clsName"]
        }


        //布局按钮
        //常量
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.size.width - 3*btnSize.width)/4

        for (i,btn) in v.subviews.enumerated() {

            let y: CGFloat = (i>2) ? (v.bounds.height - btnSize.height) : 0
            let colum = i % 3
            let x = margin * CGFloat(colum+1) + CGFloat(colum) * btnSize.width
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
        }

    }
    @IBAction func backAction(_ sender: Any) {
        //1.将滚动视图滚动到第一页
        scrollView.setContentOffset(CGPoint(x:0,y:0 ), animated: true)
        //2.两按钮合并
        backBtnCenterXCons.constant = 0
        closeBtnCenterXCons.constant = 0

        //先动画，再隐藏
       UIView.animate(withDuration: 0.25, animations: { 
        self.layoutIfNeeded()
        self.backBtn.alpha = 0
       }) { _ in
        self.backBtn.isHidden = true
        self.backBtn.alpha = 1
        }
    }


}
